"use client"

import { useState } from "react"
import { formatDistanceToNow } from "date-fns"
import { zhCN } from "date-fns/locale"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import {
  Folder,
  FileText,
  FileImage,
  FileVideo,
  FileAudio,
  File,
  MoreVertical,
  Download,
  Share2,
  Edit,
  Trash2,
  Loader2,
  Eye,
} from "lucide-react"
import { ShareDialog } from "@/components/share-dialog"
import { FilePreviewDialog } from "@/components/file-preview-dialog"

interface FileItem {
  id: number
  fileName: string
  isDirectory: boolean
  fileSize?: number
  mimeType?: string
  createdTime: string
}

interface FileListProps {
  files: FileItem[]
  isLoading: boolean
  onFolderOpen: (id: number) => void
  onDelete: (id: number) => void
  onRename: (id: number, newName: string) => void
  onDownload: (id: number, fileName: string) => void
  onRefresh: () => void
}

export function FileList({ files, isLoading, onFolderOpen, onDelete, onRename, onDownload, onRefresh }: FileListProps) {
  const [shareFile, setShareFile] = useState<FileItem | null>(null)
  const [previewFile, setPreviewFile] = useState<FileItem | null>(null)
  const [renameFile, setRenameFile] = useState<FileItem | null>(null)
  const [renameValue, setRenameValue] = useState("")
  const [deleteFile, setDeleteFile] = useState<FileItem | null>(null)

  const getFileIcon = (file: FileItem) => {
    if (file.isDirectory) return <Folder className="h-5 w-5 text-accent" />

    const mime = file.mimeType || ""
    if (mime.startsWith("image/")) return <FileImage className="h-5 w-5 text-blue-500" />
    if (mime.startsWith("video/")) return <FileVideo className="h-5 w-5 text-purple-500" />
    if (mime.startsWith("audio/")) return <FileAudio className="h-5 w-5 text-green-500" />
    if (mime.includes("text") || mime.includes("document")) return <FileText className="h-5 w-5 text-orange-500" />
    return <File className="h-5 w-5 text-muted-foreground" />
  }

  const formatFileSize = (bytes?: number) => {
    if (!bytes) return "-"
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
    if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
    return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`
  }

  const openRenameDialog = (file: FileItem) => {
    setRenameFile(file)
    setRenameValue(file.fileName)
  }

  const closeRenameDialog = () => {
    setRenameFile(null)
    setRenameValue("")
  }

  const submitRename = () => {
    if (!renameFile) return
    const trimmedName = renameValue.trim()
    if (!trimmedName || trimmedName === renameFile.fileName) {
      closeRenameDialog()
      return
    }
    onRename(renameFile.id, trimmedName)
    closeRenameDialog()
  }

  const openDeleteDialog = (file: FileItem) => {
    setDeleteFile(file)
  }

  const closeDeleteDialog = () => {
    setDeleteFile(null)
  }

  const confirmDelete = () => {
    if (!deleteFile) return
    onDelete(deleteFile.id)
    setDeleteFile(null)
  }

  const handleFileClick = (file: FileItem) => {
    if (file.isDirectory) {
      onFolderOpen(file.id)
    } else {
      setPreviewFile(file)
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    )
  }

  if (files.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center h-64 text-muted-foreground">
        <Folder className="h-16 w-16 mb-4 opacity-20" />
        <p className="text-lg">此文件夹为空</p>
        <p className="text-sm">上传文件或创建新文件夹</p>
      </div>
    )
  }

  return (
    <>
      <div className="rounded-lg border border-border bg-card">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[50%]">名称</TableHead>
              <TableHead>大小</TableHead>
              <TableHead>修改时间</TableHead>
              <TableHead className="w-[50px]"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {files.map((file) => (
              <TableRow key={file.id}>
                <TableCell className="max-w-0 w-[50%]">
                  <button
                    className="flex items-center gap-3 hover:underline text-left w-full"
                    onClick={() => handleFileClick(file)}
                  >
                    {getFileIcon(file)}
                    <span className="font-medium truncate flex-1 min-w-0">{file.fileName}</span>
                  </button>
                </TableCell>
                <TableCell className="text-muted-foreground">{formatFileSize(file.fileSize)}</TableCell>
                <TableCell className="text-muted-foreground">
                  {formatDistanceToNow(new Date(file.createdTime), {
                    addSuffix: true,
                    locale: zhCN,
                  })}
                </TableCell>
                <TableCell>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="h-8 w-8">
                        <MoreVertical className="h-4 w-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      {!file.isDirectory && (
                        <>
                          <DropdownMenuItem onClick={() => setPreviewFile(file)}>
                            <Eye className="h-4 w-4 mr-2" />
                            预览
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => onDownload(file.id, file.fileName)}>
                            <Download className="h-4 w-4 mr-2" />
                            下载
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => setShareFile(file)}>
                            <Share2 className="h-4 w-4 mr-2" />
                            分享
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                        </>
                      )}
                      <DropdownMenuItem onClick={() => openRenameDialog(file)}>
                        <Edit className="h-4 w-4 mr-2" />
                        重命名
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => openDeleteDialog(file)}
                        className="text-destructive focus:text-destructive"
                      >
                        <Trash2 className="h-4 w-4 mr-2" />
                        删除
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      <Dialog open={!!renameFile} onOpenChange={(open) => (!open ? closeRenameDialog() : undefined)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>重命名文件</DialogTitle>
            <DialogDescription>请输入新的文件名称</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <Input value={renameValue} onChange={(event) => setRenameValue(event.target.value)} autoFocus />
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={closeRenameDialog}>
              取消
            </Button>
            <Button onClick={submitRename} disabled={!renameValue.trim()}>
              确认
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog open={!!deleteFile} onOpenChange={(open) => (!open ? closeDeleteDialog() : undefined)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除该文件？</AlertDialogTitle>
            <AlertDialogDescription>
              删除后将无法恢复此文件，该操作不可撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction className="bg-destructive text-destructive-foreground hover:bg-destructive/90" onClick={confirmDelete}>
              删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {shareFile && (
        <ShareDialog file={shareFile} open={!!shareFile} onOpenChange={(open) => !open && setShareFile(null)} />
      )}

      <FilePreviewDialog
        file={previewFile}
        open={!!previewFile}
        onOpenChange={(open) => !open && setPreviewFile(null)}
        onDownload={onDownload}
      />
    </>
  )
}
